<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission('0',1)">添加权限</el-button>
        </div>
        <el-table
          border
          :data="PermissionList"
          row-key="id"
          default-expand-all
        >
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button v-if="row.type ===1" type="text" @click="addPermission(row.id,2)">添加</el-button>
              <el-button type="text" @click="hEidt(row)">编辑</el-button>
              <el-button type="text" @click="hDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 对话框 -->
      <el-dialog
        :visible.sync="showDialog"
        :title="isEdit ? '编辑' : '新增'"
        @closed="hClose"
      >
        <!-- 表单内容 -->
        <el-form ref="formRefs" label-width="100px" :model="formData" :rules="formRules">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述" prop="description">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="hSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, delPermission, updatePermission } from '@/api/permissions'
import { tranlistToTreeList } from '@/utils'
export default {
  name: 'VueHrPermissions',

  data() {
    const validateName = (rule, value, callback) => {
      // 找出所有的兄弟
      let existNameList = this.validateList.filter(item => item.pid === this.formData.pid).map(item => item.name)
      // 编辑时的校验： 名字不能取兄弟（排除自己）的名字
      // 找兄弟，排除自己
      if (this.isEdit) {
        // 找到自己的兄弟/并且排除自己
        existNameList = this.validateList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.pid).map(item => item.name)
      }
      existNameList.includes(value) ? callback(new Error(`${value}已经存在`)) : callback()
    }
    const validateCode = (rule, value, callback) => {
      let existCodeList = this.validateList.map(item => item.code)
      // 编辑时的校验: code能取自己
      if (this.isEdit) {
        // 找到除自己以外的
        existCodeList = this.validateList.filter(item => item.id !== this.formData.pid).map(item => item.code)
      }
      existCodeList.includes(value) ? callback(new Error(`${value}已经占用`)) : callback()
    }
    return {
      PermissionList: [],
      showDialog: false, // 是否显示弹层
      isEdit: false, // 控制编辑新增
      // 表单数据
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      // 表单校验数据
      validateList: [],
      formRules: {
        name: [{ message: '不能为空', required: true, trigger: 'blur' }, { validator: validateName, trigger: 'blur' }],
        code: [{ message: '不能为空', required: true, trigger: 'blur' }, { validator: validateCode, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.initPermissionList()
  },
  methods: {
    async initPermissionList() {
      try {
        const res = await getPermissionList()
        console.log(res)
        // 数据转树形结构
        this.PermissionList = tranlistToTreeList(res.data)
        this.validateList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name, code }))
        console.log(this.validateList)
      } catch (err) {
        console.log(err)
      }
    },
    // 添加权限
    addPermission(pid, type) {
      this.showDialog = true
      this.formData.pid = pid
      this.formData.type = type
      this.isEdit = false
    },
    async  doAdd() {
      try {
        const res = await addPermission(this.formData)
        console.log(res)
        this.showDialog = false
        this.initPermissionList()
      } catch (err) {
        console.log(err)
      }
    },
    // 确认添加
    hSubmit() {
      this.$refs.formRefs.validate(valid => {
        if (!valid) return
        this.isEdit ? this.hUpdate() : this.doAdd()
      })
    },
    // 关闭清空表单
    hClose() {
      this.$refs.formRefs.resetFields()
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
    },
    // 删除
    async hDel(id) {
      try {
        await delPermission(id)
        this.$message.success('删除成功')
        this.initPermissionList()
      } catch (err) {
        console.log(err)
      }
    },
    // 根据id删除
    hDelete(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.hDel(id)
      }).catch(() => {
        // 取消
      })
    },
    // 根据id更新数据
    async hUpdate() {
      try {
        const res = await updatePermission(this.formData)
        console.log(res)
        this.showDialog = false
        this.initPermissionList()
      } catch (err) {
        console.log(err)
      }
    },
    // 根据id编辑内容
    hEidt(row) {
      this.isEdit = true
      this.showDialog = true
      this.formData = { ...row }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
